<?php

namespace app\controller\admin\lol;

use app\model\api\lol\LolHeroLabel;
use app\model\api\lol\LolRelationLabel;
use app\model\api\skzy\SkzyCamp;
use GuzzleHttp\Client;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Config;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Label extends Backend
{
    protected $model;
    public function initialize()
    {
        $this->model = new LolHeroLabel();
        parent::initialize(); // TODO: Change the autogenerated stub
    }


    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->with(['hero'])->where($where)->order($order)->paginate($limit)->toArray();
            $data['data'] = array_map(function ($item){
                $icons = array_column($item['hero'],"icon");
                foreach ($icons as &$i){
                    $i = imgUrlToAbsolute($i);
                }
                $item['icon'] = implode(", ",
                    $icons);
                return $item;
            },$data['data']);
        }
        return $this->success('数据获取成功', $data);
    }


    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
        $insData = [
            'name' => $post['name'],
            'sort' => $post['sort'],
            'color' => $post['color'],
            'create_time' => date("Y-m-d H:i:s"),
            'update_time' => date("Y-m-d H:i:s"),
        ];
        try {
            Db::startTrans();
            $id = $this->model->insertGetId($insData);
            if (!$id) throw new \Exception('保存失败');
            if(!is_array($post['hero_id']))$post['hero_id'] = explode(",",$post['hero_id']);
            $label_ids = [];
            foreach ($post['hero_id'] as $item){
                $label_ids[] =[
                    'hero_id'=>$item,
                    'hero_label_id'=>$id,
                    'create_time'=>date("Y-m-d H:i:s"),
                ];
            }
            if(count($label_ids)>0)(new LolRelationLabel())->insertAll($label_ids);
            $this->clearCache();
            Db::commit();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }


    public function edit()
    {
        $post = CommonFun::filterPostData($this->request->post());
        $detail = $this->model->find($post['id']);
        empty($detail) && $this->error('数据不存在');
        $detail->name = $post['name'];
        $detail->sort = $post['sort'];
        $detail->color = $post['color'];
        try {
            Db::startTrans();
            $id = $detail->save();
            if (!$id) throw new \Exception('保存失败');
            (new LolRelationLabel())->where('hero_label_id',$post['id'])->delete();
            if(!is_array($post['hero_id']))$post['hero_id'] = explode(",",$post['hero_id']);
            $label_ids = [];
            foreach ($post['hero_id'] as $item){
                $label_ids[] =[
                    'hero_id'=>$item,
                    'hero_label_id'=>$post['id'],
                    'create_time'=>date("Y-m-d H:i:s"),
                ];
            }
            if(count($label_ids)>0)(new LolRelationLabel())->insertAll($label_ids);
            $this->clearCache();
            Db::commit();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    //查看详情
    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        if(is_object($info))$info= $info->toArray();
        $info['hero_id'] = (new LolRelationLabel())->where('hero_label_id',$id)->column("hero_id");
        $info['hero_id'] = implode(",",$info['hero_id']);
        return $this->success('获取成功', $info);
    }


    public function grab()
    {
        $client = new Client();
        $path = "/lol/getHistoryData";
        $res = $client->post(Config::get("plugin.apiGameUrl").$path,[
            'form_params' => []
        ]);
        $data = $res->getBody()->getContents();
        $result =  json_decode($data,true);
        return $this->success('获取成功',$result);
    }
}